(function (window, angular) {
  "use strict";
  angular.module("Controller.Maintenance.Repair", []).controller("RepairCtrl", [
    "$rootScope",
    "$scope",
    "ybWidget",
    "ybHttp",
    "MESG_TYPE",
    "$timeout",
    "$filter",
    "UserContextService",
    "$stateParams",
    function (
      $rootScope,
      $scope,
      ybWidget,
      ybHttp,
      MESG_TYPE,
      $timeout,
      $filter,
      UserContextService,
      $stateParams
    ) {
      $scope.photos = [];

      $scope.activeFlag = [true, false, false, false, false];
      $scope.markInfo = {
        allChecked: false,
      };
      $scope.pageInfo = {
        totalPages: 1,
        totalRows: 0,
        pageSize: 10,
        curPage: 1,
      };
      $scope.toolbarConfig = {
        showAdvanceSearch: false,
        showColConfig: false,
      };

      $scope.dataList = [];
      $scope.submitted = false;
      $scope.condition = {};

      $scope.tbConf = {
        fixedWidth: 380,
        scrollWidth: 2700,
        tableCol: [
          {
            name: "单号",
            width: 130,
            dataField: "code",
            isShow: true,
            isFixed: false,
            clickFn: "viewDetail",
          },
          {
            name: "整车编码",
            width: 160,
            dataField: "engineNo",
            isShow: true,
            isFixed: false,
          },
          {
            name: "服务类型",
            width: 100,
            dataField: "serviceTypeShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "一级服务站",
            width: 100,
            dataField: "level1ServiceStation",
            isShow: true,
            isFixed: false,
          },
          {
            name: "故障描述",
            width: 100,
            dataField: "describe",
            isShow: true,
            isFixed: false,
          },
          {
            name: "状态",
            width: 100,
            dataField: "statusShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "联系人",
            width: 100,
            dataField: "customerName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "联系方式",
            width: 100,
            dataField: "contact",
            isShow: true,
            isFixed: false,
          },
          {
            name: "车辆位置",
            width: 100,
            dataField: "address",
            isShow: true,
            isFixed: false,
          },
          /* {
            name: "营销中心",
            width: 100,
            dataField: "marketingCenterName",
            isShow: true,
            isFixed: false,
          }, */
          {
            name: "二级服务站",
            width: 100,
            dataField: "level2ServiceStation",
            isShow: true,
            isFixed: false,
          },
          {
            name: "技师",
            width: 100,
            dataField: "technicianName",
            isShow: true,
            isFixed: false,
          },
          /* {
            name: "评价状态",
            width: 100,
            dataField: "commentStatusShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "CRM传输状态",
            width: 120,
            dataField: "crmStatusShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "整车类型",
            width: 100,
            dataField: "vehicleTypeDesc",
            isShow: true,
            isFixed: false,
          }, */
          /* {
            name: "是否预约",
            width: 100,
            dataField: "appointmentShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "预约时间",
            width: 140,
            dataField: "appointmentDateShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "车牌号",
            width: 100,
            dataField: "licensePlateNumber",
            isShow: true,
            isFixed: false,
          },
          {
            name: "品牌",
            width: 120,
            dataField: "carBrand",
            isShow: true,
            isFixed: false,
          },
          {
            name: "车辆用途",
            width: 100,
            dataField: "vehicleUserDesc",
            isShow: true,
            isFixed: false,
          }, */
          {
            name: "创建人",
            width: 100,
            dataField: "createdByName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "创建时间",
            dataField: "createdTimeShow",
            width: 140,
            isShow: true,
            isFixed: false,
          },
          {
            name: "完工时间",
            dataField: "finishTimeShow",
            width: 140,
            isShow: true,
            isFixed: false,
          },
          /* {
            name: "同步时间",
            dataField: "syncTimeShow",
            width: 140,
            isShow: true,
            isFixed: false,
          }, */
          {
            name: "来源",
            width: 100,
            dataField: "channelShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "审核状态",
            width: 100,
            dataField: "completeAuditFlowStatusShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "审核时间",
            width: 140,
            dataField: "completeAuditFlowTimeShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "操作",
            isShow: true,
            isFixed: true,
          },
        ],
      };

      $scope.setFixedWidth = function () {
        $scope.tbStyle = {
          scrollLeft: {
            left: $scope.tbConf.fixedWidth + "px",
          },
        };
      };

      $scope.switchToolbar = function (toolbar) {
        if (!!$scope.toolbarConfig["show" + toolbar]) {
          $scope.toolbarConfig["show" + toolbar] = false;
        } else {
          $timeout(function () {
            $scope.toolbarConfig["show" + toolbar] = true;
          });
        }
      };

      $scope.changeTab = function (index) {
        $scope.activeFlag = [false, false, false, false, false, false];
        $scope.activeFlag[index] = true;
        $scope.submitted = false;

        if (index == 0) {
          initData();
        }
      };

      $scope.exportParam = {
        sectionUrl: ybHttp.RequestUrl("mt", "/repairForm/exportRepairs"),
        sectionParam: {ids: []},
        allUrl: ybHttp.RequestUrl("mt", "/repairForm/exportRepairsAll")
      };

      function initData() {
        $scope.is400 = false;

        $scope.isEditMode = false;

        $scope.ytdx = "";
        
        // 特机定制，营销中心是固定的
        const marketingCenterNameTemp = $scope.detailInfo.marketingCenterName;
        const marketingCenterCodeTemp = $scope.detailInfo.marketingCenterCode;

        if ($scope.isYingXiao) {
          $scope.detailInfo = {
            appointment: "0",
            marketingCenterName: marketingCenterNameTemp,
            marketingCenterCode: marketingCenterCodeTemp,
          };
        }
        if ($scope.isFWZ1) {
          $scope.detailInfo = {
            appointment: "0",
            marketingCenterName: marketingCenterNameTemp,
            marketingCenterCode: marketingCenterCodeTemp,
            level1ServiceStation: $scope.detailInfo.level1ServiceStation,
            level1ServiceStationId: $scope.detailInfo.level1ServiceStationId,
          };
        }
        if ($scope.isFWZ2) {
          $scope.detailInfo = {
            appointment: "0",
            marketingCenterName: marketingCenterNameTemp,
            marketingCenterCode: marketingCenterCodeTemp,
            level1ServiceStation: $scope.detailInfo.level1ServiceStation,
            level1ServiceStationId: $scope.detailInfo.level1ServiceStationId,
            level2ServiceStation: $scope.detailInfo.level2ServiceStation,
            level2ServiceStationId: $scope.detailInfo.level2ServiceStationId,
          };
        }

        /* $scope.carType = {}; */
        $scope.carType = { data: { code: 'chache', name: '徐工叉车', parentCode: 'DL', parentName: '道路' } };
        $scope.photos = [];

        $scope.selectedData = {};
      }

      $scope.search = function (curpage) {
        getDataList(curpage);
      };

      $scope.reset = function () {
        $scope.condition = {};
      };

      function getDataList(curPage) {
        if (!!curPage) {
          $scope.pageInfo.curPage = curPage;
        }
        var param = {
          pageSize: $scope.pageInfo.pageSize,
          pageNum: $scope.pageInfo.curPage,
          filters: $scope.condition,
        };
        ybHttp.Post("mt", "/repairForm/list", param).then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return;
          }
          $scope.markInfo.allChecked = false;
          angular.forEach(resp.value.list, function (item) {
            item.isChecked = false;
            item.appointmentDateShow = $filter("YbDate")(item.appointmentDate, "yyyy-MM-dd HH:mm:ss");
            item.createdTimeShow = $filter("YbDate")(item.createdTime, "yyyy-MM-dd HH:mm:ss");
            item.finishTimeShow = $filter("YbDate")(item.finishTime, "yyyy-MM-dd HH:mm:ss");
            item.syncTimeShow = $filter("YbDate")(item.syncTime, "yyyy-MM-dd HH:mm:ss");
            item.statusShow = $filter("RepairState")(item.status);
            item.commentStatusShow = $filter("ProgressStatus")(item.commentStatus, "commentState");
            item.crmStatusShow = $filter("ProgressStatus")(item.crmStatus, "crmState");
            item.serviceTypeShow = $filter("ServiceType")(item.serviceType);
            item.appointmentShow = $filter("TrueOrFalse")(item.appointment);
            item.channelShow = $filter("Channel")(item.channel);
            item.completeAuditFlowStatusShow = $filter("ProgressStatus")(item.completeAuditFlowStatus, "fwdAudit2");
            item.completeAuditFlowTimeShow = $filter("YbDate")(item.completeAuditFinishTime, "yyyy-MM-dd HH:mm:ss");
          });
          $scope.pageInfo.totalRows = resp.value.total;
          $scope.pageInfo.totalPages = resp.value.pages;
          $scope.dataList = resp.value.list;
        });
      }

      $scope.selectRow = function (index) {
        $scope.markInfo.curRow = index;
      };

      function checkAll() {
        var selectAll = false;
        for (var i = 0, len = $scope.dataList.length; i < len; i++) {
          if (!$scope.dataList[i].isChecked) {
            selectAll = false;
            break;
          }
          selectAll = true;
        }
        return selectAll;
      }

      $scope.selectSingle = function (item) {
        if (!item.isChecked) {
          $scope.markInfo.allChecked = false;
        } else {
          if (!checkAll()) {
            $scope.markInfo.allChecked = false;
          } else {
            $scope.markInfo.allChecked = true;
          }
        }
        getBillIds();
      };

      $scope.selectAll = function () {
        for (var i = 0, len = $scope.dataList.length; i < len; i++) {
          $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
        }
        getBillIds();
      };

      function getBillIds() {
        $scope.exportParam.sectionParam.ids = [];
        angular.forEach($scope.dataList, function (item) {
          if (!!item.isChecked) {
            $scope.exportParam.sectionParam.ids.push(item.id);
          }
        });
      }

      $scope.delData = function (delType, id) {
        var param = {
          ids: [],
        };

        if (delType === "single") {
          param.ids.push(id);
        }

        if (delType === "batch") {
          for (var i = 0, len = $scope.dataList.length; i < len; i++) {
            if (!!$scope.dataList[i].isChecked) {
              param.ids.push($scope.dataList[i].id);
            }
          }
        }
        if (param.ids.length === 0) {
          ybWidget.ShowMessage("请选择需要删除的行");
          return;
        }

        ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
          ybHttp
            .Post("mt", "/repairForm/delete", param.ids)
            .then(function (resp) {
              if (resp.code !== 0) {
                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                return;
              }
              ybWidget.ShowToaster("success", "操作成功");
              getDataList();
            });
        });
      };

      $scope.disableData = function (id) {
        ybWidget
          .ShowConfirm("确定要作废吗？", "作废原因")
          .then(function (reason) {
            let param = {
              id: id,
              disableReason: reason,
            };
            ybHttp
              .Post("mt", "/repairForm/updateDisable", param)
              .then(function (resp) {
                if (resp.code !== 0) {
                  ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                  return;
                }
                ybWidget.ShowToaster("success", "操作成功");
                getDataList();
              });
          });
      };

      $scope.addData = function () {
        $scope.changeTab(1);
      };

      $scope.isEditMode = false;
      $scope.detailInfo = {
        appointment: "0",
      };

      /* $scope.carType = {}; */
      $scope.carType = { data: { code: 'chache', name: '徐工叉车', parentCode: 'DL', parentName: '道路' } };

      $scope.editData = function (item) {
        $scope.isEditMode = true;
        item.purchaseDate = item.purchaseDate ? new Date(item.purchaseDate) : "";
        item.warrantyReleaseDate = item.warrantyReleaseDate ? new Date(item.warrantyReleaseDate) : "";
        item.appointmentDate = item.appointmentDate ? new Date(item.appointmentDate) : "";
        $scope.detailInfo = JSON.parse(JSON.stringify(item));
        /* $scope.carType.data = $scope.carTypes.find((c) => c.code == $scope.detailInfo.vehicleType); */
        $scope.carType.data = { code: 'chache', name: '徐工叉车', parentCode: 'DL', parentName: '道路' }

        $scope.photos = UserContextService.GetYbUpLoadObjConstructor($scope.detailInfo.photoList, 'minio', 'teji-weixiu/');

        $scope.selectedData = {
          gongkuang: $scope.gongkuangList.find(c => c.name == item.workCondition)
        };

        $scope.changeTab(2);
      };

      $scope.saveData = function (isValid) {
        if (!isValid) {
          $scope.submitted = true;
          return;
        }

        const { imgUploadOk: imgOk, imgUrls: imgUrlsRes } = UserContextService.HandleImgUploadInfo($scope.photos, "照片");
        if (!imgOk) return;
        $scope.detailInfo.photoList = imgUrlsRes;

        const { code, name, parentCode, parentName } = $scope.carType.data || {};
        $scope.detailInfo.vehicleType = code;
        $scope.detailInfo.vehicleTypeDesc = name;
        $scope.detailInfo.vehicleUser = parentCode;
        $scope.detailInfo.vehicleUserDesc = parentName;

        if (!$scope.isEditMode && $scope.isYingXiao && $scope.detailInfo.level1ServiceStationId) {
          $scope.detailInfo.level1ServiceStation = $scope.level1ServiceStations.find((l1) => l1.platOrgId == $scope.detailInfo.level1ServiceStationId).companyName;
        }
        if (!$scope.isEditMode && ($scope.isYingXiao || $scope.isFWZ1) && $scope.detailInfo.level2ServiceStationId) {
          $scope.detailInfo.level2ServiceStation = $scope.level2ServiceStations.find((l2) => l2.platOrgId == $scope.detailInfo.level2ServiceStationId).companyName;
        }

        const { name: gkName = '', code: gkCode = '' } = $scope.selectedData.gongkuang || {};
        $scope.detailInfo.workCondition = gkName;

        var reqUrl = "";
        if (!$scope.isEditMode) {
          if ($scope.is400 || $scope.isYingXiao) {
            if ($scope.isYingXiao) {
              $scope.detailInfo.channel = 2; // 特机新增服务单
            }
            if ($scope.is400) {
              // 此判断必须放后边
              $scope.detailInfo.channel = 1; // 400新增服务单
            }
            reqUrl = "/repairForm/insertByYn";
          }
          if ($scope.isFWZ) {
            $scope.detailInfo.channel = 3;
            reqUrl = "/repairForm/insertByDealer"; // 服务站新增服务单
          }
        } else {
          reqUrl = "/repairForm/update"; // 更新服务单
        }

        ybHttp.Post("mt", reqUrl, $scope.detailInfo).then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return;
          }
          ybWidget.ShowToaster("success", "操作成功");
          $scope.changeTab(0);
          getDataList();
        });
      };

      // 联系方式 改变时 查询 联系人信息
      /* $scope.$watch("detailInfo.contact", function (newVal) {
        if ($scope.isEditMode) return; // 编辑模式下，直接返回

        $scope.detailInfo.customerName = "";

        $scope.clearAddress();

        if (!newVal || newVal.length < 11) {
          return;
        }

        ybHttp
          .Get("mt", "/customer/getByPhone", { phone: newVal })
          .then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            resp.value = resp.value || {};
            $scope.detailInfo.customerName = resp.value.cname;
            $scope.detailInfo.address = resp.value.address;
            $scope.detailInfo.lng = resp.value.lng;
            $scope.detailInfo.lat = resp.value.lat;
            $scope.detailInfo.province = resp.value.province;
            $scope.detailInfo.city = resp.value.city;

            handleMarketingCenterInfoByAreaAndCarTypeWhenYN();
          });
      }); */

      // 查询业务伙伴【一级服务站 or 二级服务站】
      function getCompanyDealers(obj) {
        var param = {
          pageNum: 1,
          pageSize: 500,
          filters: obj,
        };
        return ybHttp
          .Post("device", "/companyDealer/listTejiWeixiu", param)
          .then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            return resp.value || {};
          });
      }

      // 当是特机（或者400跳转）时，根据整车类型的车辆用途 处理 一级服务站列表
      function handleServiceStationDLorFDLWhenYN() {
        if (!$scope.isYingXiao) {
          return;
        }
        let res = [];
        if ($scope.carType.data.parentCode == "DL") {
          res = $scope.companyFW1Dealers.filter(d => d.marketingCenterCode == $scope.detailInfo.marketingCenterCode);
        } else if ($scope.carType.data.parentCode == "FDL") {
          res = $scope.companyFW1Dealers.filter(d => d.marketingCenterCode2 == $scope.detailInfo.marketingCenterCode);
        }
        $scope.level1ServiceStations = res;
      }

      // 地图上选择位置
      $scope.selectAddress = function () {
        const options = {
          lng: $scope.detailInfo.lng,
          lat: $scope.detailInfo.lat,
          address: $scope.detailInfo.address,
        };
        ybWidget.SelwGaodeMap(options).then(function ({ a, b, c }) {
          $scope.detailInfo.address = a;
          $scope.detailInfo.province = b[0];
          $scope.detailInfo.city = b[1];
          $scope.detailInfo.lng = c[0];
          $scope.detailInfo.lat = c[1];

          /* handleMarketingCenterInfoByAreaAndCarTypeWhenYN(); */
        });
      };

      // 删除所选的位置 以及相关信息
      $scope.clearAddress = function () {
        $scope.detailInfo.address = "";
        $scope.detailInfo.province = "";
        $scope.detailInfo.city = "";
        $scope.detailInfo.lng = "";
        $scope.detailInfo.lat = "";
        /* clearMarketingCenterStationInfoWhenYN(); */
      };

      // 当是特机（或者400跳转）时，清除营销中心、服务站的相关信息
      function clearMarketingCenterStationInfoWhenYN() {
        if (!$scope.isYingXiao) {
          return;
        }
        $scope.detailInfo.marketingCenterName = "";
        $scope.detailInfo.marketingCenterCode = "";

        $scope.level1ServiceStations = [];
        $scope.detailInfo.level1ServiceStation = "";
        $scope.detailInfo.level1ServiceStationId = "";

        $scope.level2ServiceStations = [];
        $scope.detailInfo.level2ServiceStation = "";
        $scope.detailInfo.level2ServiceStationId = "";
      }

      // 整车编码 变化时 查询 车辆信息

      // 先执行ng-pattern进行格式校验
      // 校验通过，更改ng-model的值。检验不通过，ng-model的值设置成undefined
      // watch监听现在的值和原来的值是否相同。若两次值不同，执行监听函数。若两次值相同，不执行监听函数

      /* $scope.$watch("detailInfo.engineNo", function (newVal) {
        if (!$scope.isEditMode) {
          $scope.detailInfo.lifetimeWarranty = 0;
          $scope.detailInfo.licensePlateNumber = "";
          $scope.detailInfo.carBrand = "";
          $scope.carType = {};
          $scope.carType = { data: { code: 'chache', name: '徐工叉车', parentCode: 'DL', parentName: '道路' } };
        }

        if (!newVal) {
          return;
        }

        ybHttp
          .Get("mt", "/vehicle/queryByEngineNo", { engineNo: newVal })
          .then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            const valueTemp = resp.value || {};

            if (!$scope.isEditMode) {
              $scope.detailInfo.licensePlateNumber = valueTemp.licensePlateNumber;
              $scope.detailInfo.carBrand = valueTemp.carBrand;
              $scope.carType.data = $scope.carTypes.find((c) => c.code == valueTemp.vehicleType);
              $scope.carType.data = { code: 'chache', name: '徐工叉车', parentCode: 'DL', parentName: '道路' }
            }
          });
      }); */

      $scope.beforeSelMarketingCenter = function () {
        /* if ($scope.isYingXiao) {
          if (!$scope.detailInfo.address || !$scope.carType.data || !$scope.carType.data.parentName) {
            ybWidget.ShowMessage("请先选择车辆位置和整车类型");
          }
        }
        if ($scope.isFWZ) {
          if (!$scope.carType.data || !$scope.carType.data.parentName) {
            ybWidget.ShowMessage("请先选择整车类型");
          }
        } */
      };

      // 选择一级服务站前，先判断有没有选车辆位置以及整车类型
      $scope.isHasVehicleTypeAndAddress = function () {
        /* if (!$scope.detailInfo.address || !$scope.carType.data || !$scope.carType.data.parentName) {
          ybWidget.ShowMessage("请先选择车辆位置和整车类型");
        } */
      };

      // 选二级服务站前，先判断有没有选择一级服务站
      $scope.isHasFWZ1 = function () {
        if (!$scope.detailInfo.level1ServiceStationId) {
          ybWidget.ShowMessage("请先选择一级服务站");
        }
      };

      // 一级服务站变化的时候，查询二级服务站列表
      $scope.handleLevel1ServiceStationChange = function () {
        $scope.detailInfo.level2ServiceStation = "";
        $scope.detailInfo.level2ServiceStationId = "";
        if (!$scope.detailInfo.level1ServiceStationId) return;
        const param = {
          orgId: $scope.detailInfo.level1ServiceStationId, // 一级服务站的orgId
          dealerTypeList: [5, 50],
          applyStatus: 5,
        };
        getCompanyDealers(param).then(function (data) {
          $scope.level2ServiceStations = data.list || [];
        });
      };

      // 车辆用途发生改变时，处理一级服务站下拉列表数据(特机登录) 以及 营销中心数据(一级、二级服务站登录)
      $scope.$watch("carType.data.parentName", function (newVal) {
        if ($scope.isEditMode) return; // 编辑模式下，直接返回
        if ($scope.isYingXiao) {
          clearMarketingCenterStationInfoWhenYN();
        }

        if ($scope.isFWZ) {
          $scope.detailInfo.marketingCenterName = "";
          $scope.detailInfo.marketingCenterCode = "";
        }

        if (!newVal) return;

        if ($scope.carType.data.parentCode == "DL") {
          $scope.ytdx = "0";
        } else if ($scope.carType.data.parentCode == "FDL") {
          $scope.ytdx = "1";
        }

        handleMarketingCenterInfoByAreaAndCarTypeWhenYN();

        handleMarketingCenterDLorFDLWhenFWZ();
      });

      // 当是特机（或者400跳转）时，根据选择的（或者联系方式带出来的）位置信息 + 整车类型  处理营销中心以及服务站
      function handleMarketingCenterInfoByAreaAndCarTypeWhenYN() {
        if (!$scope.isYingXiao) {
          return;
        }
        /* if (!$scope.detailInfo.province || !$scope.ytdx) {
          return;
        }
        const params = {
          province: $scope.detailInfo.province,
          city: $scope.detailInfo.city,
          ytdx: $scope.ytdx,
        };
        ybHttp
          .Post("mt", "/marketingCenterArea/queryByArea", params)
          .then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            if (!resp.value) {
              ybWidget.ShowMessage(
                "所选位置没有查找到营销中心",
                MESG_TYPE.Error
              );
              return;
            }
            $scope.detailInfo.marketingCenterName = resp.value.mc;
            $scope.detailInfo.marketingCenterCode = resp.value.dm; */

            $scope.detailInfo.marketingCenterName = '徐州特机工程机械有限公司'
            $scope.detailInfo.marketingCenterCode = 'xgtejiyingxiao1115'

            const param = {
              searchCenterCode: $scope.detailInfo.marketingCenterCode,
              dealerTypeList: [5],
            };
            getCompanyDealers(param).then(function (data) {
              $scope.companyFW1Dealers = data.list || []; // 一级服务站列表

              if ($scope.carType.data && $scope.carType.data.parentName) {
                handleServiceStationDLorFDLWhenYN();
              }
            });
          /* }); */
      }

      // 根据整车类型的车辆用途 处理 营销中心
      function handleMarketingCenterDLorFDLWhenFWZ() {
        if (!$scope.isFWZ) {
          return;
        }
        $scope.detailInfo.marketingCenterName = $scope.marketingCenterMap[$scope.carType.data.parentCode].name;
        $scope.detailInfo.marketingCenterCode = $scope.marketingCenterMap[$scope.carType.data.parentCode].code;
      }

      // 获取整车类型字典数据
      function getCarTypes() {
        var param = {
          parentCode: "Vehicle_Types",
        };
        return ybHttp
          .Post("device", "/dataDictionary/searchList", param)
          .then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            const promiseArr = [];
            angular.forEach(resp.value, function (item) {
              promiseArr.push(
                ybHttp.Post("device", "/dataDictionary/searchList", {
                  parentCode: item.code,
                })
              );
            });
            return Promise.all(promiseArr).then((resp2) => {
              const resArr = [];
              angular.forEach(resp2, (r) => {
                resArr.push(...r.value);
              });
              $scope.carTypes = resArr;
            });
          });
      }

      // 当前登录用户所属企业 是服务站时，查询服务站信息（服务站等级、营销中心信息）
      function getCompanyDealerInfo(val) {
        const param = {
          platOrgId: val,
        };
        return ybHttp
          .Get("device", "/companyDealer/queryByOrgId", param)
          .then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return false;
            }
            return resp.value;
          });
      }

      // 转移营销部
      $scope.transferMarketingCenter = function (item) {
        let param = angular.copy(item);
        param.type = 1;
        param.title = "转移营销部";
        ybWidget.RepairForm(param).then(function () {
          getDataList();
        });
      };

      // 分单
      $scope.distributeOrder = function (item) {
        let param = angular.copy(item);
        if ($scope.isYingXiao) {
          param.type = 2;
        }
        if ($scope.isFWZ1) {
          param.type = 3;
        }
        param.title = "分单";
        ybWidget.RepairForm(param).then(function () {
          getDataList();
        });
      };

      // 返分单
      $scope.unDistributeOrder = function (val) {
        ybWidget
          .ShowMessage("确定要返分单吗？", MESG_TYPE.Ask)
          .then(function () {
            ybHttp
              .Post("mt", "/repairForm/returnDistribute", { id: val })
              .then(function (resp) {
                if (resp.code !== 0) {
                  ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                  return;
                }
                ybWidget.ShowToaster("success", "操作成功");
                getDataList();
              });
          });
      };

      // 派工
      $scope.dispatchWorkers = function (item) {
        let param = angular.copy(item);
        if ($scope.isFWZ1) {
          param.type = 4;
        }
        if ($scope.isFWZ2) {
          param.type = 5;
        }
        param.title = "派工";
        ybWidget.RepairForm(param).then(function () {
          getDataList();
        });
      };

      // 撤回
      $scope.unDispatchWorkers = function (val) {
        ybWidget.ShowMessage("确定要撤回吗？", MESG_TYPE.Ask).then(function () {
          ybHttp
            .Post("mt", "/repairForm/returnDispatch", { id: val })
            .then(function (resp) {
              if (resp.code !== 0) {
                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                return;
              }
              ybWidget.ShowToaster("success", "操作成功");
              getDataList();
            });
        });
      };

      function getDetail(val, isCode) {
        var reqUrl = "";
        var param = {};
        if (!isCode) {
          // 根据id查询
          reqUrl = "/repairForm/item";
          param.id = val;
        } else {
          // 根据code查询
          reqUrl = "/repairForm/queryByCode";
          param.code = val;
        }
        return ybHttp.Get("mt", reqUrl, param).then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return false;
          }
          return resp.value || {};
        });
      }
      $scope.tbConf4Log = {
        scrollWidth: 1600,
        tableCol: [
          {
            name: "单号",
            width: 130,
            dataField: "code",
            isShow: true,
            isFixed: false,
          },
          {
            name: "联系人",
            width: 100,
            dataField: "customerName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "联系方式",
            width: 100,
            dataField: "contact",
            isShow: true,
            isFixed: false,
          },
          {
            name: "车辆位置",
            width: 100,
            dataField: "address",
            isShow: true,
            isFixed: false,
          },
          {
            name: "营销中心",
            width: 100,
            dataField: "marketingCenterName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "一级服务站",
            width: 100,
            dataField: "level1ServiceStation",
            isShow: true,
            isFixed: false,
          },
          {
            name: "二级服务站",
            width: 100,
            dataField: "level2ServiceStation",
            isShow: true,
            isFixed: false,
          },
          {
            name: "技师",
            width: 100,
            dataField: "technicianName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "状态",
            width: 100,
            dataField: "statusShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "车辆",
            width: 100,
            dataField: "engineNo",
            isShow: true,
            isFixed: false,
          },
          {
            name: "组织",
            width: 100,
            dataField: "orgName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "操作人",
            width: 100,
            dataField: "createdByName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "操作时间",
            width: 140,
            dataField: "createdTimeShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "操作",
            width: 100,
            dataField: "operation",
            isShow: true,
            isFixed: false,
          },
          {
            name: "附加信息",
            width: 100,
            dataField: "additionalInformation",
            isShow: true,
            isFixed: false,
          },
        ],
      };

      $scope.itemLogs = [];

      $scope.getItemLogs = function (val) {
        getDetail(val).then(function (value) {
          if (!value) {
            return;
          }

          value.logs = value.logs || [];
          angular.forEach(value.logs, function (item) {
            item.statusShow = $filter("RepairState")(item.status);
            item.createdTimeShow = $filter("YbDate")(
              item.createdTime,
              "yyyy-MM-dd HH:mm:ss"
            );
          });
          $scope.itemLogs = value.logs;
          $scope.changeTab(3);
        });
      };

      $scope.orderObj = {};
      $scope.tabFlag = {};
      var tabFlag = {
        0: "详情",
        1: "完工补录",
      };

      $scope.viewDetail = function (val, isCode) {
        getDetail(val, isCode).then(function (value) {
          if (!value) {
            return;
          }

          value.photoListShow = UserContextService.GetYbUpLoadObjConstructor(value.photoList, 'minio', 'teji-weixiu/');
          value.orderVO = value.orderVO || {};
          value.orderVO.vehiclePhotosListShow = UserContextService.GetYbUpLoadObjConstructor(value.orderVO.vehiclePhotosList, 'minio', 'teji-weixiu/');

          $scope.orderObj = value;
          $scope.tabFlag.type = 0;
          $scope.tabFlag.name = tabFlag[0];
          $scope.changeTab(4);
        });
      };

      $scope.makeupAfterFinish = function (val) {
        getDetail(val).then(function (value) {
          if (!value) {
            return;
          }

          value.transportationKey = value.transportationKey || "";
          value.photoListShow = UserContextService.GetYbUpLoadObjConstructor(value.photoList, 'minio', 'teji-weixiu/');
          value.orderVO = value.orderVO || {};
          value.orderVO.vehiclePhotosListShow = UserContextService.GetYbUpLoadObjConstructor(value.orderVO.vehiclePhotosList, 'minio', 'teji-weixiu/');

          value.confirmMileageShow = ((value.confirmMileage || value.actualMileage || 0) / 1000).toFixed(2);
          $scope.orderObj = value;
          $scope.tabFlag.type = 1;
          $scope.tabFlag.name = tabFlag[1];
          $scope.changeTab(4);
        });
      };

      $scope.showRoute = function (startLngLat, endLngLat) {
        const options = {
          startLng: startLngLat.lng,
          startLat: startLngLat.lat,
          endLng: endLngLat.lng,
          endLat: endLngLat.lat,
        };
        ybWidget.ShowGaodeMapRoute(options);
      };

      $scope.selectDepartureLocation = function () {
        const options = {
          lng: $scope.orderObj.departureLng,
          lat: $scope.orderObj.departureLat,
          address: $scope.orderObj.departureLocation,
        };
        ybWidget.SelwGaodeMap(options).then(function ({ a, b, c }) {
          $scope.orderObj.departureLocation = a;
          $scope.orderObj.departureLng = c[0];
          $scope.orderObj.departureLat = c[1];
        });
      };

      $scope.clearDepartureLocation = function () {
        $scope.orderObj.departureLocation = "";
      };

      $scope.handleUpdateAfterFinish = function () {
        $scope.orderObj.confirmMileage =
          $scope.orderObj.confirmMileageShow * 1000;
        ybHttp
          .Post("mt", "/repairForm/updateAfterFinish", $scope.orderObj)
          .then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            ybWidget.ShowToaster("success", "操作成功");
            $scope.changeTab(0);
            getDataList();
          });
      };

      // 同步ERP
      $scope.syncErp = function (item) {
        let tipMsg = "";
        if (item.managerConfirmation == 0) {
          tipMsg = "营销部还未确认，不能传输erp";
        }
        if (item.managerConfirmation == 2) {
          tipMsg = "营销部确认该工单无效，不能传输erp";
        }
        if (tipMsg) {
          ybWidget.ShowMessage(tipMsg, MESG_TYPE.Warn);
          return;
        }

        ybHttp
          .Post("mt", "/repairForm/syncErp", { id: item.id })
          .then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            ybWidget.ShowToaster("success", "操作成功");
            getDataList();
          });
      };

      // 已经传输ERP的单子，修改整车编码
      $scope.editEngine = function (item) {
        const tip = `本功能用于在工单已经传输的情况下修改填写的错误整车编码。
                          修改整车编码的同时工单会变成未传输状态，需要先在crm系统作废原来传输的工单，然后点击“传输erp”按钮重新传输。
                          <br/><strong>确定要修改整车编码吗？</strong>`;
        ybWidget
          .ShowMessage(tip, MESG_TYPE.Ask, { isHtml: true })
          .then(function () {
            let param = angular.copy(item);
            param.title = "修改整车编码";
            param.type = 6;
            ybWidget.RepairForm(param).then(function (noRefresh) {
              !noRefresh && getDataList();
            });
          });
      };

      var btnPermissionCode = {
        REPAIRFORM_ADD: window.ActionCode.REPAIRFORM_ADD,
        REPAIRFORM_EDIT: window.ActionCode.REPAIRFORM_EDIT,
        REPAIRFORM_DISABLE: window.ActionCode.REPAIRFORM_DISABLE,
        REPAIRFORM_DELETE: window.ActionCode.REPAIRFORM_DELETE,
        REPAIRFORM_TRANSFER: window.ActionCode.REPAIRFORM_TRANSFER,
        REPAIRFORM_DISTRIBUTE: window.ActionCode.REPAIRFORM_DISTRIBUTE,
        REPAIRFORM_RETURN_DISTRIBUTE: window.ActionCode.REPAIRFORM_RETURN_DISTRIBUTE,
        REPAIRFORM_DISPATCH: window.ActionCode.REPAIRFORM_DISPATCH,
        REPAIRFORM_RETURN_DISPATCH: window.ActionCode.REPAIRFORM_RETURN_DISPATCH,
        REPAIRFORM_SYNC_ERP: window.ActionCode.REPAIRFORM_SYNC_ERP,
        REPAIRFORM_UPDATE_AFTER_FINISH: window.ActionCode.REPAIRFORM_UPDATE_AFTER_FINISH,
        REPAIRFORM_AUDIT: window.ActionCode.REPAIRFORM_AUDIT,
      };

      $scope.btnPermission = {
        REPAIRFORM_ADD: true,
        REPAIRFORM_EDIT: true,
        REPAIRFORM_DISABLE: true,
        REPAIRFORM_DELETE: true,
        REPAIRFORM_TRANSFER: true,
        REPAIRFORM_DISTRIBUTE: true,
        REPAIRFORM_RETURN_DISTRIBUTE: true,
        REPAIRFORM_DISPATCH: true,
        REPAIRFORM_RETURN_DISPATCH: true,
        REPAIRFORM_SYNC_ERP: true,
        REPAIRFORM_UPDATE_AFTER_FINISH: true,
        REPAIRFORM_AUDIT: true,
      };

      function setBtnPermission() {
        for (var key in btnPermissionCode) {
          $scope.btnPermission[key] = UserContextService.CheckPermission([
            btnPermissionCode[key],
          ]);
        }
      }

      // 选择整车编码
      $scope.selectEngineNo = function() {
        const options = {
          title: '整车编码',
          service: 'mt',
          url: '/productArchive/listWhenRepairForm',
          keyWords: [{ label: '整车编码', field: 'vehicleNo' }],
          fields: [
            {
              name: '整车编码',
              dataField: 'vehicleNo',
              width: "50%"
            },
            {
              name: '产品型号',
              dataField: 'productModel',
              width: "50%"
            },
          ]
        }
        ybWidget.DataSelector(options).then(function (data) {
          delete data.id
          delete data.address
          delete data.province
          delete data.city

          if (!data.dunwei) {
            ybWidget.ShowMessage('请联系特机管理员维护吨位数据后，再创建服务单！', MESG_TYPE.Error);
            return
          }

          const { vehicleNo, contract, phone } = data
          data.engineNo = vehicleNo
          data.customerName = contract
          data.contact = phone
          data.purchaseDate = data.purchaseDate ? new Date(data.purchaseDate) : "";
          data.warrantyReleaseDate = data.warrantyReleaseDate ? new Date(data.warrantyReleaseDate) : ""

          $scope.detailInfo = {
            ...$scope.detailInfo,
            ...data
          };

          ybHttp.Get("mt", `/productArchive/iotInfo?vehicleNo=${vehicleNo}`).then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            }

            const valueT = resp.value || {};
            
            let hasVehicleIotGpsT;
            const { encLon, encLat, address, province, city } = valueT
            if (!encLon) {
              hasVehicleIotGpsT = 0;
            } else {
              hasVehicleIotGpsT = 1;
            }
            $scope.detailInfo.hasVehicleIotGps = hasVehicleIotGpsT;

            $scope.detailInfo.lng = encLon;
            $scope.detailInfo.lat = encLat;
            $scope.detailInfo.address = address;
            $scope.detailInfo.province = province;
            $scope.detailInfo.city = city;
          });
        })
      };

      // 审核单据
      $scope.auditData = function(val) {
        const params = {
          id: val
        }
        ybWidget.AuditMsg({
          passCb: function(val) {
            params.auditStatus = 1
            params.auditRemark = val
            return handleAudit(params)
          },
          refuseCb: function(val) {
            params.auditStatus = 2
            params.auditRemark = val
            return handleAudit(params)
          }
        })
      };

      function handleAudit(param) {
        return ybHttp.Post("mt", "/repairForm/completeAudit", param).then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return;
          }
          ybWidget.ShowToaster('success', '操作成功');
          getDataList();
        });
      }

      // 获取更换备件的定位高度
      $scope.getHeight = function(hasPhotos, hasVehiclePhotos) {
        return hasPhotos && hasVehiclePhotos ? 610 : ((hasPhotos || hasVehiclePhotos) ? 560 : 505)
      };

      $scope.viewGss = function(val) {
        window.open(`https://xgss.xcmg.com/mobile/#/pin/${val}/384`)
      };

      $scope.serviceTypeList = [];
      // 获取服务单类型
      function getServiceTypes() {
        return ybHttp.Get("mt", "/repairForm/serviceTypes").then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return;
          }
          $scope.serviceTypeList = resp.value || [];
        });
      }

      $scope.$watch('detailInfo.purchaseDate', function(newVal) {
        if (!!newVal && $scope.detailInfo.serviceType == 2 && !!$scope.detailInfo.guaranteePeriod) {
          const param = {
            engineNo: $scope.detailInfo.engineNo,
            purchaseDate: newVal
          }
          ybHttp.Post("mt", "/repairForm/vehicleWarrantCal", param).then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            const valueT = resp.value || {}
            const { warrantyReleaseDate, warrantyStatus } = valueT
            $scope.detailInfo.warrantyReleaseDate = warrantyReleaseDate ? new Date(warrantyReleaseDate) : ''
            $scope.detailInfo.warrantyStatus = warrantyStatus
          });
        }
      });

      $scope.checkDate = function (obj, startFiled, endFiled) {
        var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
        if (!!timeFormatObj.tStart) {
            obj[startFiled] = timeFormatObj.tStart;
        }
        if (!!timeFormatObj.tEnd) {
            obj[endFiled] = timeFormatObj.tEnd;
        }
      };

      $scope.selectedData = {};
      $scope.gongkuangList = [];
      // 获取工况字典数据源
      function getGongKuangs(){
        var service = "mt";
        var reqUrl = "/serviceBasicDataAgent/list";
        var param = { filters:{ pCode:"WXCLGK" } };
        ybHttp.Post(service, reqUrl, param).then(function (resp) {
            if (resp.code !== 0) {
                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                return;
            }
            $scope.gongkuangList = resp.value.list;
        });
      }

      function getUrlParams(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var parm = window.location.hash.split("?")[1];
        if (parm == null) return null;
        var r = parm.match(reg);
        if (r == null) return null;
        return decodeURIComponent(r[2]);
      }

      (function () {
        var code = getUrlParams("code");
        if (code) {
          $rootScope.pageDisabled = true;
          $scope.viewDetail(code, true);
          return;
        }

        UserContextService.SetBtnPermission(setBtnPermission);
        $scope.setFixedWidth();

        if ($stateParams.engineNo) {
          $scope.condition.engineNo = $stateParams.engineNo;
        }

        getDataList();

        getServiceTypes();
        getGongKuangs();

        /* var contact = getUrlParams("contact");
        getCarTypes().then(() => {
          if (!!contact) {
            // 400新增 跳转而来
            $scope.detailInfo.callerNum = contact;
            $scope.detailInfo.contact = contact;
            $scope.detailInfo.engineNo = getUrlParams("engineNo");
            $scope.detailInfo.drivenDistance = getUrlParams("drivenDistance");
            $scope.detailInfo.purchaseDate = getUrlParams("purchaseDate");
            $scope.detailInfo.describe = getUrlParams("describe");
            $scope.is400 = true;
          }
          $scope.$apply();
        }); */
        if ($scope.isFWZ1) {
          $scope.detailInfo.level1ServiceStation = $scope.curOrg.companyNameAsDealer;
          $scope.detailInfo.level1ServiceStationId = $scope.curOrg.orgId;
          $scope.handleLevel1ServiceStationChange(); // 复用一级服务站变化时查询二级服务站列表信息 （根据一级服务站orgId 查询二级服务站列表）

          $scope.marketingCenterMap = {
            DL: {
              code: $scope.curOrg.bindMarketingCenterCode,
              name: $scope.curOrg.bindMarketingCenterName,
            },
            FDL: {
              code: $scope.curOrg.bindMarketingCenterCode2,
              name: $scope.curOrg.bindMarketingCenterName2,
            },
          };
        }
        if ($scope.isFWZ2) {
          $scope.detailInfo.level2ServiceStation = $scope.curOrg.companyNameAsDealer;
          $scope.detailInfo.level2ServiceStationId = $scope.curOrg.orgId;
          getCompanyDealerInfo($scope.curOrg.parentOrgId).then(function (data) {
            // 根据二级服务站上的信息 查询一级服务站信息 以及 营销中心信息
            if (!data) return;
            $scope.detailInfo.level1ServiceStation = data.companyName;
            $scope.detailInfo.level1ServiceStationId = data.platOrgId;

            $scope.marketingCenterMap = {
              DL: {
                code: data.marketingCenterCode,
                name: data.marketingCenterName,
              },
              FDL: {
                code: data.marketingCenterCode2,
                name: data.marketingCenterName2,
              },
            };
          });
        }

        /* if (!!contact) {
          // 有该字段，说明是400跳转而来
          $scope.changeTab(1);
        } */
      })();
    },
  ]);
})(window, window.angular);
